<?php

namespace Encore\Admin\Actions\Custom;

use Doctrine\DBAL\Exception;
use Encore\Admin\Auth\Database\Menu;
use Illuminate\Support\Str;
use Schema;

trait AutoMatchAdminMenuTrait
{
    /**
     *  action match the menu id
     * @param array $actions
     * @return array
     * @throws Exception
     */
    protected function actionsMatch(array $actions): array
    {
        $menus = Menu::all();
        //all table names
        $tables = Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();

        //tables to models
        $models = array_map(function ($table) {
            return Str::studly(Str::singular($table));
        }, $tables);

        //menu id => model name
        $modelMenuIds = collect($models)->map(function ($model) use ($menus) {
            $menu = $menus->where('uri', Str::snake(Str::plural($model), '-'))->first();
            return [
                'menuId' => data_get($menu, 'parent_id') ?: data_get($menu, 'id'),
                'model'  => $model,
            ];
        })->pluck('menuId', 'model')
            ->toArray();

        //match admin menu id
        return collect($actions)->map(function ($action) use ($models, $modelMenuIds) {
            $actionName = Str::ucfirst(Str::camel(Str::replace('.', '-', $action['slug'])));
            foreach ($models as $model) {
                if (Str::contains($actionName, $model)) {
                    if (!$action['admin_menu_id']) {
                        $action['admin_menu_id'] = $modelMenuIds[$model];
                    }
                }
            }
            return $action;
        })->toArray();
    }

    /**
     * route match menu id
     * @param array $methodLists
     * @return array
     */
    protected function routesMatches(array $methodLists): array
    {
        $menus = Menu::all();
        return collect($methodLists)->map(function ($list) use ($menus) {
            $tableToUri = str_replace('_', '-', $list['table']);
            /** @var Menu $menu */
            $menu = $menus->where('uri', $tableToUri)->first();
            if (is_null($menu)) {
                $menu = $menus->where('uri', 'like', Str::before($tableToUri,'-'))->first();
            }
            if (!is_null($menu)) {
                $list['admin_menu_id'] = $menu->parent_id ?: $menu->id;
                $list['table_name'] = $menu->title;
            }
            return $list;
        })->toArray();
    }

}